let express = require('express');
let router = express.Router();

const taskService = require('../service/taskService');

// 引入jwt验证方法的中间件
const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');
router.use(checkJWTMiddleWare);

// 添加任务接口
router.post('/addTask', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { name, description, count } = req.body;
    // 删除comment中所有的空白字符
    let format_name = name.replace(/\s+/g, '');
    let format_description = description.replace(/\s+/g, '');

    if (!format_name || !format_description || !count) {
        return res.status(400).json({ success: false, msg: "参数错误" });
    }
    let result = await taskService.addTask(uid, name, description, count);
    res.status(result.success ? 200 : 400).json(result);
});

// 删除任务接口
router.post('/deleteTask', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { taskId } = req.body;
    if (!taskId) {
        return res.status(400).json({ success: false, msg: "参数错误" });
    }
    let result = await taskService.deleteTask(uid, taskId);
    res.status(result.success ? 200 : 400).json(result);
});

// 设置任务已完成接口
router.post('/setTaskComplete', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { taskId } = req.body;
    if (!taskId) {
        return res.status(400).json({ success: false, msg: "参数错误" });
    }
    let result = await taskService.setTaskComplete(uid, taskId);
    res.status(result.success ? 200 : 400).json(result);
});

// 查询所有任务接口
router.get('/getTaskList', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let result = await taskService.getTaskList(uid);
    res.status(result.success ? 200 : 400).json(result);
});

// 分页获取所有任务签到接口
router.get('/getAllTaskCheckin', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let page = parseInt(req.query.page || 1);
    let result = await taskService.getAllTaskCheckin(uid, page);
    res.status(result.success ? 200 : 400).json(result);
});

module.exports = router;